package com.umgsai.wx.backend.manager;

import com.alibaba.fastjson.JSON;
import com.umgsai.wx.backend.model.MailAuthenticator;
import com.umgsai.wx.backend.model.MailSenderInfo;
import com.umgsai.wx.backend.model.request.SendHtmlMailRequest;
import com.umgsai.wx.backend.model.request.SendSimpleMailRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

@Slf4j
@Component
public class MailManager {

    private static final String mailServerHost = "smtp.ym.163.com";
    private static final String mailServerPort = "465";
    private static final String mailUsername = "pcf@xxxxx.com";
    private static final String mailPassword = "xxxxx";
    private static final String fromAddress = "pcf@xxxx.com";

    private MailSenderInfo getMailSenderInfo() {
        MailSenderInfo mailSenderInfo = new MailSenderInfo();
        mailSenderInfo.setMailServerHost(mailServerHost);
        mailSenderInfo.setMailServerPort(mailServerPort);
        mailSenderInfo.setValidate(true);
        mailSenderInfo.setUserName(mailUsername);
        mailSenderInfo.setPassword(mailPassword);
        mailSenderInfo.setFromAddress(fromAddress);
        return mailSenderInfo;
    }

    public void sendSimpleMail(SendSimpleMailRequest request) {
        try {
            MailSenderInfo mailSenderInfo = getMailSenderInfo();

            mailSenderInfo.setToAddress(request.getMailTo());
            mailSenderInfo.setSubject(request.getMailSubject());
            mailSenderInfo.setContent(request.getMailText());

            sendMail(mailSenderInfo, true);


        } catch (Exception e) {
            log.error("sendSimpleMail error, request={}", JSON.toJSONString(request), e);
        }

    }

    public void sendHtmlMail(SendHtmlMailRequest request) {
        try {
            MailSenderInfo mailSenderInfo = getMailSenderInfo();

            mailSenderInfo.setToAddress(request.getMailTo());
            mailSenderInfo.setSubject(request.getMailSubject());
            mailSenderInfo.setContent(request.getMailText());

            sendMail(mailSenderInfo, false);


        } catch (Exception e) {
            log.error("sendHtmlMail error, request={}", JSON.toJSONString(request), e);
        }
    }

    private void sendMail(MailSenderInfo mailSenderInfo, Boolean isTextMail) throws Exception {
        MailAuthenticator authenticator = null;
        Properties properties = mailSenderInfo.getProperties();
        if (mailSenderInfo.isValidate()) {
            // 如果需要身份认证，则创建一个密码验证器
            authenticator = new MailAuthenticator(mailSenderInfo.getUserName(), mailSenderInfo.getPassword());
        }
        Session sendMailSession = Session.getDefaultInstance(properties, authenticator);
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address fromAddress = new InternetAddress(mailSenderInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(fromAddress);
        // 创建邮件的接收者地址，并设置到邮件消息中
        Address toAddress = new InternetAddress(mailSenderInfo.getToAddress());
        mailMessage.setRecipient(Message.RecipientType.TO, toAddress);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailSenderInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // 设置邮件消息的主要内容
        String mailContent = mailSenderInfo.getContent();

        // 纯文本格式
        if (isTextMail) {
            mailMessage.setText(mailContent);
        } else {
            // HTML格式
            Multipart mp = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();
            body.setContent(mailContent, "text/html;charset=utf-8");
            mp.addBodyPart(body);
            mailMessage.setContent(mp);
        }
//        message.saveChanges();
        Transport transport = sendMailSession.getTransport("smtp");
        transport.connect(properties.getProperty("mail.smtp.host"), properties.getProperty("username"), properties.getProperty("password"));
        transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
        transport.close();

//        Transport.send(mailMessage);

        log.info("邮件发送成功. 标题：{} 收件人：{}", mailSenderInfo.getSubject(), mailSenderInfo.getToAddress());
    }
}
